const fs = require('fs')
const path = require('path')
const log = require('../log')
const os = require('os')

const configFile = os.homedir() + '/.tts/auth'

if (!fs.existsSync(configFile)) {
    console.debug("缓存不存在,创建...")
    fs.mkdirSync(path.dirname(configFile), {recursive: true})
    fs.writeFileSync(configFile, "{}")
}

let clientId
let clientSecret
let accessToken
let expireTime
let expired = true

let loaded = false

loadFile(configFile)

/**
 * 加载文件
 */
function loadFile() {
    if (loaded) {
        return
    }
    const s = fs.readFileSync(configFile, 'utf-8')
    const obj = JSON.parse(s);
    log.debug("获取到缓存数据:", s)
    clientId = obj.clientId
    clientSecret = obj.clientSecret
    accessToken = obj.accessToken
    expireTime = obj.expireTime
    expired = expireTime < new Date().getTime()
    loaded = true
}

function string() {
    const str = JSON.stringify({
        clientId: clientId,
        clientSecret: clientSecret,
        expireTime: expireTime,
        accessToken: accessToken
    })
    log.debug("当前数据: ", str)
    return str
}

/**
 * 持久化clientId和secret
 * @param obj
 */
function storeClientIdAndSecret(obj) {
    loadFile()
    clientId = obj.clientId
    clientSecret = obj.clientSecret
    log.debug("保存clientId: %s,secret: %s", clientId, clientSecret)
    fs.writeFileSync(configFile, string())
}

/**
 * 持久化token
 * @param obj
 */
function storeToken(obj) {
    loadFile()
    accessToken = obj.access_token
    expireTime = new Date().getTime() + obj.expires_in * 1000
    log.debug("保存accessToken: %s,expireTime: %s", accessToken, expireTime)
    fs.writeFileSync(configFile, string())
}

exports = module.exports = {
    clientId,
    clientSecret,
    accessToken,
    expireTime,
    expired,
    storeToken,
    storeClientIdAndSecret
}

